package com.intelligent.ispc.common.persistence.jdbc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by Peter on 15/11/25.
 */
public class JdbcPageable<T> {
    private final Logger logger = LoggerFactory.getLogger(JdbcPageable.class);

    //Default page size
    public static final int DEFAULT_PAGE_SIZE = 10;

    private int size;
    private int total;
    private int totalPages;
    private int currentPage;
    private int begin;
    private int end;
    private List<T> content;

    public JdbcPageable() {
    }

    public JdbcPageable(int pageSize, int pageNumber) {
        this.setCurrentPage(pageNumber+1);
        this.setSize(pageSize);
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public List<T> getContent() {
        return content;
    }

    public void setContent(List<T> content) {
        this.content = content;
    }

    public int getTotalPages() {
        return totalPages;
    }

    public void setTotalPages() {
        if (total % size == 0) {
            this.totalPages = total / size;
        } else {
            this.totalPages = (total / size) + 1;
        }
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getBegin() {
        return begin;
    }

    public void setBegin() {
        this.begin = (currentPage-1) * size;
    }

    public int getEnd() {
        return end;
    }

    public void setEnd() {
        if (total < size) {
            this.end = total;
        } else if ((total % size == 0) || (total % size != 0 && currentPage < totalPages)) {
            this.end = currentPage * size -1;
        } else if (total % size != 0 && currentPage == totalPages) {
            //the last page.
            this.end = total;
        }
    }

    public Iterator<T> iterator() {
        return content.iterator();
    }

    public boolean hasContent() {
        return !content.isEmpty();
    }

    public boolean hasNextPage() {
        return getCurrentPage() < getTotalPages();
    }

    public boolean isLastPage() {
        return !hasNextPage();
    }

    public boolean hasPreviousPage() {
        return getCurrentPage() > 1;
    }

    public boolean isFirstPage() {
        return !hasPreviousPage();
    }
}
